<?php


namespace App\Http\Controllers\Api;


use App\Http\Controllers\Controller;
use App\Http\Resources\AdminResource;
use App\Models\Admin;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;

class AuthController extends Controller
{
    /**
     * 登录
     * @param Request $request
     * @return \Illuminate\Contracts\Routing\ResponseFactory|\Illuminate\Http\Response
     */
    public function login(Request $request)
    {
        $username = $request->get('username');
        $password = $request->get('password');
        $admin = Admin::query()->where('username', $username)->first();
        if (!$admin) {
            return response(['code' => 403, 'message' => '该用户不存在！', 'success' => false], 200);
        }
        $correctPassword = Hash::check(
            $password,$admin->password
        );
        if (!$correctPassword){
            return response()->json(['error' => '密码错误'], 422);
        }
        $token = $admin->createToken('MyApp')->accessToken;
        return response(['code' => 200, 'message' => '登录成功！', 'success' => true, 'data' => ['token' => $token]], 200);
    }


    public function info(){
        return new AdminResource(Auth::user());
    }

}
